package com.bestcem.xm.om.util;

import com.bestcem.xm.om.enums.TemplateParamEnum;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * mybatis表达式替换类，参照org.apache.ibatis.parsing.GenericTokenParser进行修改
 *
 * @author zhangfeng <feng.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2021/11/29 11:01
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TextParseUtil {

    /**
     * 默认的起始标识符
     */
    public static final String OPEN_TOKEN = "${";

    /**
     * 默认的结尾标识符
     */
    public static final String CLOSE_TOKEN = "}";

    /**
     * 根据起始结束标志符来替换text中的值,如果替换列表为空,以空字符串代替
     *
     * @param text     目标字符串
     * @param paramMap 替换参数列表
     * @return java.lang.String
     * @author zhangfeng <feng.zhang@idiaoyan.com>
     * @date 2021/11/29 11:03
     */
    public static String parseEl(String text, Map<String, Object> paramMap) {
        try {
            return parse(text, OPEN_TOKEN, CLOSE_TOKEN, paramMap);
        } catch (Exception e) {
            log.error("解析处理失败 paramMap:{}  e:{}", paramMap, e);
        }
        return text;
    }

    /**
     * 根据起始结束标志符来替换text中的值,如果替换列表为空,以空字符串代替
     *
     * @param text       目标字符串
     * @param openToken  起始标识符
     * @param closeToken 结尾标识符
     * @param paramMap   替换参数列表
     * @return java.lang.String
     * @author zhangfeng <feng.zhang@idiaoyan.com>
     * @date 2021/11/29 11:03
     */
    private static String parse(String text, String openToken, String closeToken, Map<String, Object> paramMap) {
        if (text == null || text.isEmpty()) {
            return "";
        }
        // search open token
        int start = text.indexOf(openToken);
        if (start == -1) {
            return text;
        }

        List<String> linkList = (List<String>) paramMap.get(TemplateParamEnum.LINK_LIST.getName());
        int i = 0;
        if (Objects.nonNull(paramMap)) {
            linkList = (List<String>) paramMap.get(TemplateParamEnum.LINK_LIST.getName());
        }

        char[] src = text.toCharArray();
        int offset = 0;
        final StringBuilder builder = new StringBuilder();
        StringBuilder expression = null;
        do {
            if (start > 0 && src[start - 1] == '\\') {
                // this open token is escaped. remove the backslash and continue.
                builder.append(src, offset, start - offset - 1).append(openToken);
                offset = start + openToken.length();
            } else {
                // found open token. let's search close token.
                if (expression == null) {
                    expression = new StringBuilder();
                } else {
                    expression.setLength(0);
                }
                builder.append(src, offset, start - offset);
                offset = start + openToken.length();
                int end = text.indexOf(closeToken, offset);
                while (end > -1) {
                    if (end > offset && src[end - 1] == '\\') {
                        // this close token is escaped. remove the backslash and continue.
                        expression.append(src, offset, end - offset - 1).append(closeToken);
                        offset = end + closeToken.length();
                        end = text.indexOf(closeToken, offset);
                    } else {
                        expression.append(src, offset, end - offset);
                        break;
                    }
                }
                if (end == -1) {
                    // close token was not found.
                    builder.append(src, start, src.length - start);
                    offset = src.length;
                } else {
                    if (Objects.nonNull(paramMap)) {
                        String key = expression.toString();
                        Object val = paramMap.get(key);
                        if (TemplateParamEnum.isLink(key)) {
                            builder.append(linkList.get(i));
                            i++;
                        } else if (Objects.nonNull(val)) {
                            builder.append(val);
                        }
                    }
                    offset = end + closeToken.length();
                }
            }
            start = text.indexOf(openToken, offset);
        } while (start > -1);
        if (offset < src.length) {
            builder.append(src, offset, src.length - offset);
        }
        return builder.toString();
    }

    /**
     * 解析text获取占位符对应的参数Map
     *
     * @param text 目标字符串
     * @return java.lang.String
     * @author zhangfeng <feng.zhang@idiaoyan.com>
     * @date 2021/11/29 11:03
     */
    public static Map<String, Object> convertParamMap(String text) {
        return convertParamMap(text, OPEN_TOKEN, CLOSE_TOKEN);
    }

    /**
     * 解析text获取占位符对应的参数Map
     *
     * @param text       目标字符串
     * @param openToken  起始标识符
     * @param closeToken 结尾标识符
     * @return java.lang.String
     * @author zhangfeng <feng.zhang@idiaoyan.com>
     * @date 2021/11/29 11:03
     */
    private static Map<String, Object> convertParamMap(String text, String openToken, String closeToken) {
        Map<String, Object> paramMap = new HashMap<>(16);
        if (text == null || text.isEmpty()) {
            return paramMap;
        }
        // search open token
        int start = text.indexOf(openToken);
        if (start == -1) {
            return paramMap;
        }
        char[] src = text.toCharArray();
        int offset = 0;
        StringBuilder expression = null;
        do {
            if (start > 0 && src[start - 1] == '\\') {
                // this open token is escaped. remove the backslash and continue.
                offset = start + openToken.length();
            } else {
                // found open token. let's search close token.
                if (expression == null) {
                    expression = new StringBuilder();
                } else {
                    expression.setLength(0);
                }
                offset = start + openToken.length();
                int end = text.indexOf(closeToken, offset);
                while (end > -1) {
                    if (end > offset && src[end - 1] == '\\') {
                        // this close token is escaped. remove the backslash and continue.
                        expression.append(src, offset, end - offset - 1).append(closeToken);
                        offset = end + closeToken.length();
                        end = text.indexOf(closeToken, offset);
                    } else {
                        expression.append(src, offset, end - offset);
                        break;
                    }
                }
                if (end == -1) {
                    // close token was not found.
                    offset = src.length;
                } else {
                    handleParam(expression.toString(), paramMap);
                    offset = end + closeToken.length();
                }
            }
            start = text.indexOf(openToken, offset);
        } while (start > -1);
        return paramMap;
    }

    /**
     * 对于el表达式的值做处理
     *
     * @param param
     * @param paramMap
     * @return void
     * @author zhangfeng <feng.zhang@idiaoyan.com>
     * @date 2021/12/7 14:26
     */
    private static void handleParam(String param, Map<String, Object> paramMap) {
        String val = TemplateParamEnum.getParam(param);
        // 如果是待处理的参数，则放入参数map
        if (StringUtils.isNotBlank(val)) {
            // 如果是链接类型，则放入链接列表
            if (!param.equals(val)) {
                List<String> linkList = (List<String>) paramMap.getOrDefault(TemplateParamEnum.LINK_LIST.getName(), new ArrayList<>());
                linkList.add(val);
                paramMap.put(TemplateParamEnum.LINK_LIST.getName(), linkList);
            } else {
                paramMap.put(param, val);
            }
        }
    }
}
